# -*- coding: utf-8 -*-

from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from ..extensions import db
# from datetime import datetime

__all__ = ['UserModel']

class UserModel(db.Model, UserMixin):
    """data model"""
    # 表名
    __tablename__ = 'tb_users'
    # 主键(id)不会自动创建，需手动创建
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(20), unique=True, index=True, nullable=False)
    age = db.Column(db.Integer, default=18)
    password_hash = db.Column(db.String(128), nullable=False)
    email = db.Column(db.String(20), unique=True, nullable=False)
    create_time = db.Column(db.DateTime, default=db.func.now())
    update_time = db.Column(db.DateTime, default=db.func.now(), onupdate=db.func.now())

    def __init__(self, *args, **kwargs):
            super(UserModel, self).__init__(*args, **kwargs)

    def set_password(self, password):  # 用来设置密码的方法，接受密码作为参数
            self.password_hash = generate_password_hash(password,"pbkdf2")  # 将生成的密码保持到对应字段

    def validate_password(self, password):  # 用于验证密码的方法，接受密码作为参数
        return check_password_hash(self.password_hash, password)  # 返回布尔值
    
    def to_json(self):
        return {
            'id': self.id,
            'name': self.name,
            'age': self.age,
            'email': self.email,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S')
        }